<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" /> <!--- 强制升级https，避免混合错误  --->
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>TAS</title>
  <link href="../css/bootstrap.min.css" rel="stylesheet">
  <style type="text/css">
    .group {
      padding: 1.5rem;
      margin-right: 0;
      margin-left: 0;
      border-width: 1px;
      border-top-left-radius: .25rem;
      border-top-right-radius: .25rem;

      position: block;
      padding: 1rem;
      margin: 1rem -.75rem 0;
      border: solid #dee2e6;
      border-width: 1px 0 0;
    }
  </style>
  <script src="../js/plotly-2.18.0.min.js"></script>
  <script src="../js/jquery-3.6.0.min.js"></script>
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="col-md-10" id="fig_container">
        <div id="fig_main" style="height:700px;"></div>
      </div>

      <div class="col-md-2">
        <label><input type="radio" name="model" value="Volcanic" checked>Volcanic</label>
        <label><input type="radio" name="model" value="Plutonic">Plutonic</label>
        <div class="form-check">
          <input class="form-check-input" type="checkbox" value="" id="chkLegend" checked>
          <label class="form-check-label" for="chkLegend">
            Legend
          </label>
        </div>
        <div class="form-check">
          <input class="form-check-input" type="checkbox" checked value="" id="chkDetail">
          <label class="form-check-label" for="chkDetail">
            Detail
          </label>
        </div>
        <div class="form-check">
          <input class="form-check-input" type="checkbox" value="" id="chkIrvine">
          <label class="form-check-label" for="chkIrvine">
            Irvine
          </label>
        </div>
        <label class="form-check-label" for="groupField4TAS">
          Group by:
        </label>
        <select class="form-select" id="groupField4TAS">
          <option selected value="-1">No Group</option>
        </select>
        <hr />
        <div id="numberConfig4TAS" class="group" style="width:300px; display:none;">
          <div id='groupNumberConfig4TAS'>

          </div>
          <button onclick="redrawNumberGroup4TAS();" style="margin-top:30px;margin-left:50px;"> ReDraw </button>
        </div>

        <div id='groupSetting4TAS' class="group" style="width:300px;">
        </div>
        <div class="d-grid gap-2">

        </div>
      </div>
    </div>
  </div>
  <script src="../js/plotly-2.18.0.min.js"></script>
  <script>
    //尝试绘制TAS图
    var lineDiv = document.getElementById('fig_main');

    var LocationAreas4Plutonic = [[[41, 3], [37, 3], [35, 9], [37, 14], [52.5, 18], [52.5, 14], [48.4, 11.5], [45, 9.4], [41, 7]],
    [[41, 0], [41, 3], [45, 3], [45, 0]],
    [[41, 3], [41, 7], [45, 9.4], [49.4, 7.3], [45, 5], [45, 3]],
    [[45, 9.4], [48.4, 11.5], [53, 9.3], [49.4, 7.3]],
    [[48.4, 11.5], [52.5, 14], [57.6, 11.7], [53, 9.3]],
    [[52.5, 14], [52.5, 18], [57, 18], [63, 16.2], [61, 13.5], [57.6, 11.7]],
    [[45, 0], [45, 2], [52, 5], [52, 0]],
    [[45, 2], [45, 5], [52, 5]],
    [[45, 5], [49.4, 7.3], [52, 5]],
    [[49.4, 7.3], [53, 9.3], [57, 5.9], [52, 5]],
    [[53, 9.3], [57.6, 11.7], [61, 8.6], [63, 7], [57, 5.9]],
    [[57.6, 11.7], [61, 13.5], [63, 16.2], [71.8, 13.5], [61, 8.6]],
    [[61, 8.6], [71.8, 13.5], [69, 8], [63, 7]],
    [[52, 0], [52, 5], [57, 5.9], [57, 0]],
    [[57, 0], [57, 5.9], [63, 7], [63, 0]],
    [[63, 0], [63, 7], [69, 8], [77.3, 0]],
    [[77.3, 0], [69, 8], [71.8, 13.5], [85.9, 6.8], [87.5, 4.7]],
    [[77.3, 0], [87.5, 4.7]],// [90, 4.7],// [90, 0]],
    ];
    var LocationAreas4Volcanic = [[[41, 0.5], [41, 3], [41, 7], [45, 9.4], [48.4, 11.5], [52.5, 14]],
    [[45, 0.5], [45, 3], [45, 5], [49.4, 7.3], [53, 9.3], [57.6, 11.7], [61, 13.5], [61.92, 14]],
    [[52, 0.5], [52, 5], [57, 5.9], [63, 7], [69, 8], [69, 13]],
    //  [[39.3, 0],[43.28, 1.91], [48.18,4.08], [51.02, 5.22], [53.72, 6.13], [56.58, 7], [60.47, 8], [66.82, 9], [77.15, 10]],   //这个是Irvine？
    [[69, 8], [76.5, 0.5]],
    [[41, 3], [45, 3]],
    [[45, 5], [52, 5]],
    [[52, 0.5], [52, 5], [49.4, 7.3], [45, 9.4]],
    [[57, 0.5], [57, 5.9], [53, 9.3], [48.4, 11.5]],
    [[63, 0.5], [63, 7], [57.6, 11.7], [52.5, 14], [48.07, 16]]];

    //标签位置
    var Locations = [[39, 10], [43, 1.5], [44, 6], [47.5, 3.5], [49.5, 1.5], [49, 5.2], [49, 9.5], [54, 3], [53, 7],
    [53, 12],
    [60, 4],
    [57, 8.5], [57, 14], [67, 5], [65, 12], [67, 9], [75, 9], [85, 1], [55, 18.5]];
    var Labels4Volcanic = ['F', 'Pc', 'U1', 'Ba', 'Bs', 'S1', 'U2', 'O1', 'S2', 'U3', 'O2', 'S3', 'Ph', 'O3',
      'T',
      'Td', 'R', 'Q', 'S/N/L'];
    var Labels4Plutonic = ['F', 'Pc', 'U1', 'Ba', 'Bs', 'S1', 'U2', 'O1', 'S2', 'U3', 'O2', 'S3', 'Ph', 'O3',
      'T',
      'Td', 'R', 'Q', 'T/U/I'];

    var data = buildData4TAS();

    // 图的layout设置
    var layout = {
      title: {
        text: 'TAS (total alkali–silica) diagram Volcanic/Intrusive (Wilson et al. 1989)',
        font: {
          size: 30,
          family: 'arial'
        }
      },
      xaxis: {
        rangemode: 'normal',
        title: {
          text: 'SiO2 wt %',
          font: {
            size: 30,
            family: 'arial'
          }
        },
        tickmode: 'array',
        tickvals: [40, 50, 60, 70, 80, 90],
        showgrid: false,
        range: [30, 90],
        showline: true,
        ticklen: 8,
        tickfont: {
          size: 20,
          family: 'arial'
        }
      },
      yaxis: {
        rangemode: 'normal',
        title: {
          text: 'Na2O + K2O wt %',
          font: {
            size: 30,
            family: 'arial',
          },
        },
        tickmode: 'array',
        tickvals: [0, 5, 10, 15, 20],
        showgrid: false,
        range: [0, 20],
        showline: true,
        ticklen: 8,
        tickfont: {
          size: 20,
          family: 'arial'
        }
      }
    };

    var config4TAS = {
      toImageButtonOptions: {
        format: 'svg', // one of png, svg, jpeg, webp
        filename: 'TAS',
        height: 700,
        width: 1300,
        scale: 1 // Multiply title/legend/axis/canvas sizes by this factor
      }
    };

    Plotly.newPlot(lineDiv, data, layout, config4TAS);

    // 构造基础data中的trace
    function buildData4TAS() {
      var model = $('input:radio[name="model"]:checked').val();
      var detail = $('#chkDetail').prop("checked");
      // console.log('detail:',detail);
      var mapdata = [];  //初始化数组
      if (model == 'Volcanic') {
        //分界线
        for (var line of LocationAreas4Volcanic) {
          var xlist = [], ylist = [];
          for (var i = 0; i < line.length; i++) {
            xlist.push(line[i][0]);
            ylist.push(line[i][1]);
          }
          var traceA = {
            x: xlist,
            y: ylist,
            type: 'scatter',
            fill: 'none',
            mode: 'lines',
            line: {
              color: 'rgb(128, 128, 128)',
            },
            showlegend: false,
          };
          mapdata.push(traceA);
        }
        //分界线添加完毕
        if (detail == true) {
          // 画标签
          var xlist = [], ylist = [];
          for (var i = 0; i < Locations.length; i++) {
            xlist.push(Locations[i][0]);
            ylist.push(Locations[i][1]);
          }
          var traceLabel = {
            x: xlist,
            y: ylist,
            type: 'scatter',
            fill: 'none',
            textposition: 'top left',
            mode: 'text',
            text: Labels4Volcanic,
            showlegend: false,
          };
          mapdata.push(traceLabel);
        }

      } else {
        //Plutonic
        //分界线
        for (var line of LocationAreas4Plutonic) {
          var xlist = [], ylist = [];
          for (var i = 0; i < line.length; i++) {
            xlist.push(line[i][0]);
            ylist.push(line[i][1]);
          }
          var traceA = {
            x: xlist,
            y: ylist,
            type: 'scatter',
            fill: 'none',
            mode: 'lines',
            line: {
              color: 'rgb(128, 128, 128)',
            },
            showlegend: false,
          };
          mapdata.push(traceA);
        }
        //分界线添加完毕
        if (detail == true) {
          // 画标签

          var xlist = [], ylist = [];
          for (var i = 0; i < Locations.length; i++) {
            xlist.push(Locations[i][0]);
            ylist.push(Locations[i][1]);
          }
          var traceLabel = {
            x: xlist,
            y: ylist,
            type: 'scatter',
            fill: 'none',
            textposition: 'top left',
            mode: 'text',
            text: Labels4Plutonic,
            showlegend: false,
          };
          mapdata.push(traceLabel);
        }
      }
      return mapdata;


    }


    // 判断记录是否有效
    function isValidItem4TAS(item) {
      if (item.hasOwnProperty('SiO2') && item.hasOwnProperty('Na2O') && item.hasOwnProperty('K2O')
        && item.SiO2 != null && item.Na2O != null && item.K2O != null) {
        return true;
      } else {

        return false;
      }
    }
    //格式化字符串函数
    String.format = function () {
      if (arguments.length == 0)
        return null;
      var str = arguments[0];
      for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
      }
      return str;
    };

    var rtnColumns4TAS = [];  //返回得列名数组
    var numberColumns4TAS = [];  //返回的数字列名数组
    var rtnData4TAS;//返回的数据
    var traceList4TAS = []; //缓存所有的trace（不包括底图的）
    var numberSpanConfig4TAS = [];   //缓存所有的数字字段的分段设置

    // 重绘所有图
    function redrawMap4TAS() {
      var mydata = buildData4TAS();
      //添加traceLayer
      var drawdata = mydata.concat(traceList4TAS);
      Plotly.newPlot(lineDiv, drawdata, layout, config4TAS);
    };

    //注册分组id变化事件
    $("#groupField4TAS").change(function () {
      var selIndex = ($(this).val());
      $('#numberConfig4TAS').hide(); //默认隐藏起来，如果是数字再打开
      if (selIndex == -1) {  //此时不分组
        //console.log('不分组');
        buildNoGroup4TAS(); //不分组数据
      } else { //按照所选字段进行分组
        var filterField = rtnColumns[selIndex];
        //此时需要判断是数字字段还是文本字段，如果是数字字段，则需要弹出新的ui来进行设置分段取值
        var index = numberColumns4TAS.indexOf(filterField);
        if (index > -1) {
          //数字字段
          buildNumberGroup4TAS(filterField);
        } else {
          //字符串字段
          buildStrGroup4TAS(filterField);
        }
      }//筛选条件结束

      //重绘全图
      redrawMap4TAS();
    });

    /*注册分组Marker有关属性的事件监听
   function registerListener4Group(){
      $("input[name='colorSelector4TAS']").change(function(){
         var title=$(this).data('label');
         console.log(title,$(this).val());
           //遍历查找对应的图层进行修改
           for (trace of  traceList){
           console.log('重绘', trace.title.text);
             if(trace.title.text ==title){
             trace.marker.color=$(this).val();
             redrawMap4TAS();//改变之后重绘
             console.log('重绘', trace.title.text);
             return true;
           }
         }
      });
      $("select[name='shapeSelector4TAS']").change(function(){
         var title=$(this).data('label');
         console.log(title,$(this).val());
           //遍历查找对应的图层进行修改
           for (trace of  traceList){
           console.log('重绘', trace.title.text);
             if(trace.title.text ==title){
             trace.marker.symbol=$(this).val();
             redrawMap4TAS();//改变之后重绘
             console.log('重绘', trace.title.text);
             return true;
           }
         }
      });
     $("input[name='sizeSelector4TAS']").change(function(){
         var title=$(this).data('label');
         console.log(title,$(this).val());
           //遍历查找对应的图层进行修改
           for (trace of  traceList){
           console.log('重绘', trace.title.text);
             if(trace.title.text ==title){
             trace.marker.size=$(this).val();
             redrawMap4TAS();//改变之后重绘
             console.log('重绘', trace.title.text);
             return true;
           }
         }
      });
   };  */

    //注册分组Marker有关属性的事件监听
    function registerListener4GroupTAS() {
      $("input[name='colorSelector4TAS']").change(function () {
        var title = $(this).data('label');
        console.log(title, $(this).val());
        //遍历查找对应的图层进行修改
        for (trace of traceList4TAS) {
          console.log('重绘', trace.title.text);
          if (trace.title.text.replace("&le;", "≤").replace("&lt;", "<") == title) {
            trace.marker.color = $(this).val();
          }
        }
        redrawMap4TAS();//改变之后重绘
        console.log('重绘', trace.title.text);
        return true;
      });
      $("select[name='shapeSelector4TAS']").change(function () {
        var title = $(this).data('label');
        console.log(title, $(this).val());
        //遍历查找对应的图层进行修改
        for (trace of traceList4TAS) {
          if (trace.title.text.replace("&le;", "≤").replace("&lt;", "<") == title) {
            trace.marker.symbol = $(this).val();
            console.log('symbol:', $(this).val());
          }
        }
        redrawMap4TAS();//改变之后重绘
        console.log('重绘', trace.title.text);
        return true;
      });
      $("input[name='sizeSelector4TAS']").change(function () {
        var title = $(this).data('label');
        console.log(title, $(this).val());
        //遍历查找对应的图层进行修改
        for (trace of traceList4TAS) {
          console.log('重绘', trace.title.text);
          if (trace.title.text.replace("&le;", "≤").replace("&lt;", "<") == title) {
            trace.marker.size = $(this).val();
          }
        }
        redrawMap4TAS();//改变之后重绘
        console.log('重绘', trace.title.text);
        return true;
      });
    }; //函数结束  ---注册分组Marker有关属性的事件监听

    // 添加一个新的数字分组html组件
    function addNumberGroupHtml4TAS(groupName, index) {
      var myhtml = buildNumberGroupHtml4TAS(groupName.toString(), index + 1);
      // console.log($('#numberConfig4ACNK').css('display'),'构造数字分组：',myhtml);
      $('#groupNumberConfig4TAS').append(myhtml);
      //把上一个的+按钮禁用掉
      var myAdd = String.format("#btnAddSpan4TAS-{0}", index);
      $(myAdd).hide();


    }//函数结束——添加一个新的数字分组html组件

    //移除一个数字分组html组件
    function removeNumberGroupHtml4TAS(index) {
      if ($('#groupNumberConfig4TAS').children().length <= 1) {
        alert("the last one can't be removed");
        return true;
      }
      var myId = String.format("#numberSpan4TAS-{0}", index);
      $(myId).empty();
      $(myId).remove();
      //把最后一个的添加按钮显示出来
      var lastDiv = $('#groupNumberConfig4TAS').children().last();
      var lastIndex = lastDiv.data('label');
      var myAdd = String.format("#btnAddSpan4TAS-{0}", lastIndex);
      $(myAdd).show();
    }

    // 数字字段引发的重绘
    function redrawNumberGroup4TAS() {
      //首先得到数字字段分组的设置
      numberSpanConfig4TAS = [];  ////清空旧的，从ui中重新获取
      $.each($('#groupNumberConfig4TAS').children(), function (index, item) {
        let numSpan = {};
        // console.log(index, ":", $(item).data("label"));
        //从item中进一步查找子元素
        var startitem = $(item).find("input[name='numberStart4TAS']");
        var enditem = $(item).find("input[name='numberEnd4TAS']");
        //判断是否是有效的设置，如果全空则无效
        numSpan.startValue = $(startitem).val().trim();
        numSpan.endValue = $(enditem).val().trim();
        if (numSpan.startValue == "" && numSpan.endValue == "")
          return false;
        //记录一下field
        numSpan["field"] = $(startitem).data("label");

        numberSpanConfig4TAS.push(numSpan);
      });
      //console.log("Number Span:",numberSpanConfig4ACNK);

      //如果没有有效分组，则按照不分组进行处理
      if (numberSpanConfig4TAS.length == 0) {
        console.log("没有有效数字分组，直接按照不分组重绘");
        buildNoGroup4TAS();
        //重绘全图
        redrawMap4TAS();
        return true;  //直接退出
      }
      // 按照数值字段进行分组
      //置空 分组名称及分组结果的数组
      var groupNames = [], groupValues = [];  // 置空
      for (var i = 0; i < rtnData4TAS.length; i++) {
        var item = rtnData4TAS[i];
        //只有有效的数据才需要分组
        if (isValidItem4TAS(item)) {

          var x = item.SiO2;
          var y = item.Na2O + item.K2O;

          var hasMatched = false;
          // 对所有数字分组进行筛选，看看当前数据是否在某一个分组范围内，如果在，则加入到对应的groupList中
          for (var j = 0; j < numberSpanConfig4TAS.length; j++) {
            let myNumSpan = numberSpanConfig4TAS[j];
            let filterKey = myNumSpan.field.trim();

            if (item.hasOwnProperty(myNumSpan.field.trim()) == false || item[myNumSpan.field] == "undefined")
              break;  //没有这个字段，则直接当作others处理

            //console.log("初始化filterKey:",myNumSpan.field,"   ,  numberSpan:",myNumSpan," 类型",typeof(myNumSpan.startValue));
            //var flag =false;
            if (myNumSpan.hasOwnProperty("startValue") && typeof (myNumSpan.startValue) == "string" && myNumSpan.startValue != "") {
              //console.log("进入startValue逻辑",item,myNumSpan.field,item[myNumSpan.field]);
              filterKey = myNumSpan.startValue + "&lt;" + filterKey;
              if (item[myNumSpan.field] <= parseFloat(myNumSpan.startValue)) {// 如果比起始值还小
                //console.log("小于最小：",item,myNumSpan.field,item[myNumSpan.field]);
                continue;   //继续下一轮
              }
            }
            if (myNumSpan.hasOwnProperty("endValue") && typeof (myNumSpan.endValue) == "string" && myNumSpan.endValue != "") {
              //console.log("进入endValue逻辑",item[myNumSpan.field] , parseFloat(myNumSpan.endValue), item,myNumSpan.field,item[myNumSpan.field]);
              filterKey = filterKey + "&le;" + myNumSpan.endValue;
              if (parseFloat(item[myNumSpan.field]) > parseFloat(myNumSpan.endValue)) { // 如果比起始值还小
                //console.log("大于最大：",item,myNumSpan.field,item[myNumSpan.field]);
                continue;   //继续下一轮
              }
            }
            //console.log("filterKey:",filterKey,myNumSpan);
            //满足条件
            hasMatched = true;   // 已经匹配上了，不会出现在Others中
            //检查是否已经在分组名称里，如果不在则添加
            var groupValueList = { 'x': [], 'y': [] };
            if (groupNames.indexOf(filterKey) >= 0) {
              groupValueList = groupValues[filterKey];
              // console.log('取出来的:',groupValueList);
            } else {
              //把自己添加进去
              groupNames.push(filterKey);
              groupValues[filterKey] = groupValueList;
            }
            groupValueList['x'].push(x);
            groupValueList['y'].push(y);
          } //分组循环结束
          //如果没有匹配上的，则统一加到Other中
          if (hasMatched == false) {
            // console.log("进入others逻辑");
            let keystr = "Others";
            var groupValueList = { 'x': [], 'y': [] };
            if (groupNames.indexOf(keystr) >= 0) {
              groupValueList = groupValues[keystr];
              // console.log('取出来的:',groupValueList);
            } else {
              //把自己添加进去
              groupNames.push(keystr);
              groupValues[keystr] = groupValueList;
            }
            groupValueList['x'].push(x);
            groupValueList['y'].push(y);
          }
        } // end --if 有效
      }// end -for  遍历所有数据

      //循环结束
      //console.log('group:',groupNames);
      //console.log('values',groupValues); 
      //清空所有的筛选字段子元素，然后重新添加
      buildGroupData4TAS(groupNames, groupValues);
      //重绘全图
      redrawMap4TAS();

    }// 函数结束


    // 注册事件，模型切换
    $("input:radio[name='model']").change(function () {
      redrawMap4TAS();
    });

    // 注册事件，是否显示图例
    $('#chkLegend').change(function () {
      var show = $(this).prop('checked');
      for (trace of traceList) {
        trace.showlegend = show;
      }
      //redrawMap4TAS();	  //刷新很消耗资源，暂时注掉
      Plotly.react();//刷新图
      //  console.log(show);
    });

    // 生成分组的html界面
    function buildGroupHtml4TAS(groupName, color, index = 0) {
      var html = ' <div class="row" >\
                                                <label for="color" style="font-size:0.5em;margin-right:10px; width:90px;">{0}</label> \
				                                <input  name="colorSelector4TAS" id="color-{0}"  type="color"   style="width:30px;margin-right:10px;" data-label="{0}" value="{1}" title="Choose color "> \
				                                <select   style="width:80px;margin-right:10px;" id="shape-tas-{2}" name="shapeSelector4TAS"  data-label="{0}"  title="choose the shape"> \
														<option  value="0">circle</option> \
														<option value="1">square</option> \
														<option value="2">diamond</option> \
														<option value="3">cross</option> \
														<option value="4">x</option> \
														<option selected value="5">triangle-up</option> \
														<option value="6">triangle-down</option> \
														<option value="7">triangle-left</option> \
														<option value="8">triangle-right</option> \
														<option value="9">triangle-ne</option> \
														<option value="10">triangle-se</option> \
														<option value="11">triangle-sw</option> \
														<option value="12">triangle-nw</option> \
														<option value="13">pentagon</option> \
														<option value="14">hexagon</option> \
														<option value="15">hexagon2</option> \
														<option value="16">octagon</option> \
														<option value="17">star</option> \
														<option value="18">hexagram</option> \
				                                </select>\
				                                <input  type="number" step="1" name="sizeSelector4TAS"  data-label="{0}"  style="width:40px;margin-left:10px;"  min="3" max="15" value="5" title="set the size of shape"> \
                                             </div>';
      return String.format(html, groupName, color, index);
    }

    // 构造数字分组的html页面
    function buildNumberGroupHtml4TAS(groupName, index = 0) {
      var html = ' <div class="row"  id="numberSpan4TAS-{1}"   data-label="{1}"  >\
                                                <label for="color" style="font-size:0.5em;margin-right:10px; width:70px;">{0}：</label> \
				                                 <input  type="number"  step="0.01" name="numberStart4TAS"  data-label="{0}"  style="width:60px;"   title="the start value"> \
				                                 <label>-</label> \
				                                <input  type="number"   step="0.01"  name="numberEnd4TAS"  data-label="{0}"  style="width:60px;"   title="the end value"> \
  												<button  id="btnRemoveSpan4TAS-{1}"  onclick="removeNumberGroupHtml4TAS({1});"  style="margin-left:10px; width:30px;">  - </button> \
												<button  id="btnAddSpan4TAS-{1}"  onclick="addNumberGroupHtml4TAS(\'{0}\',{1}); "  style="margin-left:10px; width:30px;">  + </button> \
                                  </div>';
      return String.format(html, groupName, index);

    } //函数结束---构造数字分组的html页面


    //  构建不分组数据
    function buildNoGroup4TAS() {
      //console.log('不分组');
      //此时需要清空分组选项，然后直接显示trace数据
      $('#groupSetting4TAS').empty();
      html = buildGroupHtml4TAS("No Group", "#00008B", 5); //默认第五个
      $('#groupSetting4TAS').append(html);
      //生成trace    
      var xlist = [], ylist = [];
      for (var i = 0; i < rtnData4TAS.length; i++) {
        var item = rtnData4TAS[i];
        if (isValidItem4TAS(item)) {
          // console.log(item);   
          xlist.push(item.SiO2);
          ylist.push(item.Na2O + item.K2O);
        }
      }
      //console.log(xlist,ylist);
      //生成trace，并加进去，然后更新图
      var traceLayer = {
        x: xlist,
        y: ylist,
        name: "No Group (" + xlist.length + " )",
        type: 'scatter',
        showlegend: $('#chkLegend').prop('checked'),
        fill: 'none',
        textposition: 'top left',
        mode: 'markers',
        marker: {
          'symbol': 5,
          'size': 5,
          'color': 'rgb(0,0,139)',
        },
        title: 'No Group'
      };
      traceList4TAS = [];
      traceList4TAS.push(traceLayer);
      registerListener4GroupTAS();// 注册监听器
      return false; //直接退出
    }  // 不分组函数结束





    //构建数字型分组ui
    function buildNumberGroup4TAS(filterField) {
      //清空旧的
      $('#numberConfig4TAS').show();
      $('#groupNumberConfig4TAS').empty();
      var myhtml = buildNumberGroupHtml4TAS(filterField, 0);
      // console.log($('#numberConfig4ACNK').css('display'),'构造数字分组：',myhtml);
      $('#groupNumberConfig4TAS').append(myhtml);
    }// 函数结束——构建数字型分组ui

    // 构造分组绘图数据
    function buildGroupData4TAS(groupNames, groupValues) {
      //清空所有的筛选字段子元素，然后重新添加
      $('#groupSetting4TAS').empty();
      var colorTable = ['#00008B', '#00FEFE', '#E00098', '#00EE00', '#121212', '#212121'];  //此处内置允许的的颜色查找表，回头补充科研时常用的颜色。 *************todo************

      traceList4TAS = [];//清空已有的traceList

      for (var i = 0; i < groupNames.length; i++) {
        var groupName = groupNames[i];

        html = buildGroupHtml4TAS(groupName, colorTable[i % colorTable.length], i + 5);
        $('#groupSetting4TAS').append(html);
        //添加后对shape设置默认选择值
        var myid = String.format('#shape-tas-{0}', i);
        try {
          $(myid).val(i % 19);  //此时是为了规避特殊字符导致无法初始化这个。todo*****后期应该把空格给去掉
        } catch (e) {
          console.log("发生异常:" + e)
        }

        // 生成trace list
        //生成trace，并加进去，然后更新图
        var traceLayer = {
          x: groupValues[groupName]['x'],
          y: groupValues[groupName]['y'],
          type: 'scatter',
          fill: 'none',
          showlegend: $('#chkLegend').prop('checked'),
          name: groupName.replace('&le;', "≤") + " (" + groupValues[groupName]['x'].length + " )",
          textposition: 'top left',
          mode: 'markers',
          marker: {
            'symbol': (i + 5) % 19,
            'size': 5,
            'color': colorTable[i % colorTable.length],
          },
          title: groupName

        };
        traceList4TAS.push(traceLayer);
      }
      //筛选条件结束
      registerListener4GroupTAS();// 注册监听器

    }

    //构建字符型分组
    function buildStrGroup4TAS(filterField) {
      // console.log('分组字段：',filterField);
      //置空 分组名称及分组结果的数组
      var groupNames = [], groupValues = [];
      for (var i = 0; i < rtnData4TAS.length; i++) {
        var item = rtnData4TAS[i];
        if (isValidItem4TAS(item)) {

          var x = item.SiO2;
          var y = item.Na2O + item.K2O;

          //有效数据则进行处理，无效则掠过
          //获取分组字段的值
          var filterValue = item[filterField];
          //console.log('filterValue',filterValue);
          //null或者‘’认为是 null
          if (filterValue == null || filterValue == '')
            filterValue = 'null';
          filterValue = filterValue.replace(/\s*/g, ""); //去除所有空格，包括头尾和中间的。中间的容易导致jquery定位错误

          //检查是否已经在分组名称里，如果不在则添加
          var groupValueList = { 'x': [], 'y': [] };
          if (groupNames.indexOf(filterValue) >= 0) {
            groupValueList = groupValues[filterValue];
            // console.log('取出来的:',groupValueList);
          } else {
            //把自己添加进去
            groupNames.push(filterValue);
            groupValues[filterValue] = groupValueList;
          }
          groupValueList['x'].push(x);
          groupValueList['y'].push(y);
        }
      }
      //循环结束
      //console.log('group:',groupNames);
      //console.log('values',groupValues); 
      buildGroupData4TAS(groupNames, groupValues);
    }// 构建字符型分组函数结束


    //外部设置数据的主函数

    function setData2TAS(columns, data, numbercolumns) {
      rtnColumns4TAS = columns;
      rtnData4TAS = data; //把返回值赋予全局变量
      numberColumns4TAS = numbercolumns;
      //把列名添加到分组列表
      //清空列名列表
      $("#groupField4TAS").empty();
      //添加一个不分组
      $("#groupField4TAS").append('<option selected value="-1">No Group</option>');

      for (var i = 0; i < rtnColumns4TAS.length; i++) {
        $("#groupField4TAS").append("<option value=" + i + ">" + rtnColumns4TAS[i] + "</option>");
      }
      //按照不分组先显示所有数据
      buildNoGroup4TAS();
      redrawMap4TAS();
    }  //setdata2TAS 函数结束		
  </script>


  <script>

    // 异步获取数据---测试
    $.ajax({
      type: "get",        // 请求方式
      // url: "https://petrology.deep-time.org/fastapi/kdata/Igneous_Rock/geowind@126.com",
      url: "http://127.0.0.1:3000/admin/loaddata/yjyview",
      data: { 'boundary': "", 'condition': "", 'scope': 'private', 'start': 0, 'length': 5000 },
      dataType: "json",   // 预期返回一个 json 类型数据
      success: function (rtn) {   // data是形参名，代表返回的数据
        //处理返回数据
        //把列名添加到分组列表
        rtnColumns = rtn.columns;
        setData2TAS(rtn.columns, rtn.data, rtn.numbercolumns);
      }
    });

    //    console.log("rtnData",rtn.data)
  </script>

</body>

</html>